package Templates;

sub new
{
	my ($class)        = @_;		
	my $self           = {};
	$self->{group_id}  = 0;
	$self->{realm_id}  = 0;

	bless $self, 'Templates';
	return $self;

}

sub newFromDB
{
    my ($class, $template_id)   = @_;
    my $self	           = {};
    
    my $kit_db  = new KIT_DB();

    my $stmt    = "SELECT id, subject, content, realm_id, active FROM templates WHERE id = $template_id";
    my $hashref = $kit_db->GetSingleRow($stmt);

    $self->{template_id}   = $hashref->{id};
    $self->{content}       = $hashref->{content};
    $self->{subject}       = $hashref->{subject};
    $self->{realm_id}      = $hashref->{realm_id};
    $self->{active}        = $hashref->{active};

    bless $self, 'Templates';
    return $self;
}

#	-- See also SaveNewContent
sub update
{
    my ($self)	= @_;

    my $template_id = $self->{'template_id'};

    my $content	    = $self->{'content'};
       $content     =~ s/\'/\'\'/g;

    my $subject	    = $self->{'subject'};
       $subject     =~ s/\'/\'\'/g;

    my $stmt	= "UPDATE templates 
                   SET    content='$content', subject='$subject'
                   WHERE  id = $template_id";

    my $kit_db  = new KIT_DB();
    return $kit_db->Update($stmt);
}

sub insert_new
{
    my ($self)	= @_;

    my $stmt	= "INSERT INTO templates (content, subject, realm_id) 
                   VALUES (\'$self->{content}\', \'$self->{subject}\', $self->{realm_id})";

    #	-- Return the new record_id
    my $kit_db  = new KIT_DB();
    return $kit_db->Insert($stmt);
}

sub get_template_list {
    my $self            = shift;
    my @template_list   = ();

    my $stmt    = "SELECT   id, subject, content, realm_id, active 
                   FROM     templates
                   WHERE    realm_id = " . $self->{realm_id};

    my $kit_db  = new KIT_DB();
    my @rows	= $kit_db->GetMultipleRows($stmt);

    foreach (@rows) {
        my %templates_hash = (
                template_id => sprintf ("%02d", $_->[0]),
                subject     => $_->[1],
                content     => $_->[2],
                realm_id    => $_->[3],
                active      => $_->[4],
        );
        push @template_list, \%templates_hash;
#         print "subj = ". $_->[1] . "<br>";
    }
    return @template_list;
}

sub exists {
    my ($self, $t_id)   = @_;

    return -1 if !$t_id;
    my $stmt    = "SELECT count(*) AS ret_val FROM templates WHERE template_id = $t_id";
    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

sub set_subject {
    my ($self, $subject)  = @_;

    $subject        =~ s/\'/\\'/g;
    $self->{subject}  = $subject;
    return;
}

sub set_content {
    my ($self, $content)  = @_;

    $content            =~ s/\'/\\'/g;
    $self->{content}    = $content;

    return;
}

sub set_realm_id {
    my ($self, $realm_id)   = @_;
    $self->{realm_id}       = $realm_id;
    return;
}
1;